package com.example.service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.example.bean.TextMessage;
import com.example.util.CommonEnum;
import com.example.util.JsonToMap;
import com.example.util.MapUtil;
import com.example.util.httpSendUtil;


@Component
public class weiChatService {
	public String getAccess_token(){

		//给微信平台发get请求获取access_token
		String content = "";
		String appId=CommonEnum.WXAppId.getName();
			String WXSecret=CommonEnum.WXSecret.getName();
		while(content.contains("errcode") || "".equals(content)){
			String WXSTokenUrl=CommonEnum.WXSTokenUrl.getName();
    		WXSTokenUrl=MapUtil.getSpellUrl(WXSTokenUrl,new String[]{appId,WXSecret});
			content = httpSendUtil.sendGet(WXSTokenUrl);
		}
		Map<String,Object> map = JsonToMap.jsonToMapSingle(content);
		CommonEnum.WXAccessToken.setName(map.get("access_token").toString());
		
		System.out.println("重新获取access_token:"+CommonEnum.WXAccessToken.getName());
		return map.get("access_token").toString();
	
	}
	public String dealEvent(HttpServletRequest request,HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		/** 读取接收到的xml消息 */
		StringBuffer sb = new StringBuffer();
		InputStream is = request.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String s = "";
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		String xml=sb.toString();
		 // 正常的微信处理流程
		String result = "";
		Map<String,Object>mapresult=MapUtil.parseXml(xml);
		//判断类型
		String ToUserName=mapresult.get("ToUserName").toString();
		String FromUserName=mapresult.get("FromUserName").toString();//此值相当于openid
		String MsgType=mapresult.get("MsgType").toString();
		if("event".equals(MsgType)){//点击事件
			String event=mapresult.get("Event").toString();
			if(CommonEnum.Unsubscribe.getName().equals(event)){//取消关注
				/**
				 * 取消关注的时候，对openId进行解绑
				**/
				//weixinService.UnsubscribeRealseBangDing(FromUserName);
				return null;
			}else if(CommonEnum.Subscribe.getName().equals(event)){//关注
				/**
				 *关注的时候，自动回复
				**/
				String appId=CommonEnum.WXAppId.getName();
	    		String BandDingJumpUrl=MapUtil.getConfigValue("baseurl")+"/bingDingInit";
	    		BandDingJumpUrl=URLEncoder.encode(BandDingJumpUrl,"UTF-8");//URL转码
	    		String WXSBandDingTokenUrl=MapUtil.getSpellUrl(CommonEnum.WXSBandDingTokenUrl.getName(),new String[]{appId,BandDingJumpUrl});
				result="欢迎关注康明斯天远官网微信公众号，绑定账户请<a href=\""+WXSBandDingTokenUrl+"\">点击这里</a>";
				TextMessage tm=new TextMessage();
				tm.setFromUserName(ToUserName);
				tm.setToUserName(FromUserName);
				tm.setMsgType(CommonEnum.Text.getName());
				tm.setCreateTime(new Date().getTime());
				tm.setContent(result);
				result=JsonToMap.getText(tm);
			}else if(CommonEnum.Location.getName().equals(event)){
				String Latitude=mapresult.get("Latitude").toString();//经度
				String Longitude=mapresult.get("Longitude").toString();//维度
				String Precision=mapresult.get("Precision").toString();//精度
				return null;
			}else if(CommonEnum.Click.getName().equalsIgnoreCase(event)){
				String EventKey=mapresult.get("EventKey").toString();
				Map<String,Object>param=new HashMap<String,Object>();
				if(MapUtil.getConfigValue("product-key").equals(EventKey)){//图文消息:产品介绍
					param.put("fromuser",FromUserName);
					param.put("touser",ToUserName);
					param.put("msgtype","news");
					param.put("title",MapUtil.getConfigValue("product-title"));
					param.put("description",MapUtil.getConfigValue("product-description"));
					param.put("picurl",MapUtil.getConfigValue("baseurl")+MapUtil.getConfigValue("product-picurl"));
					param.put("url",MapUtil.getConfigValue("product-url"));
					result=JsonToMap.getImageText(param);
				}
				if(MapUtil.getConfigValue("downIems-key").equals(EventKey)){//图文消息:道路版APP
					param.put("fromuser",FromUserName);
					param.put("touser",ToUserName);
					param.put("msgtype","news");
					param.put("title",MapUtil.getConfigValue("downIems-title"));
					param.put("description",MapUtil.getConfigValue("downIems-description"));
					param.put("picurl",MapUtil.getConfigValue("baseurl")+MapUtil.getConfigValue("downIems-picurl"));
					param.put("url",MapUtil.getConfigValue("downIems-url"));
					result=JsonToMap.getImageText(param);
				}
				if(MapUtil.getConfigValue("downGcic-key").equals(EventKey)){//图文消息:机械版APP
					param.put("fromuser",FromUserName);
					param.put("touser",ToUserName);
					param.put("msgtype","news");
					param.put("title",MapUtil.getConfigValue("downGcic-title"));
					param.put("description",MapUtil.getConfigValue("downGcic-description"));
					param.put("picurl",MapUtil.getConfigValue("baseurl")+MapUtil.getConfigValue("downGcic-picurl"));
					param.put("url",MapUtil.getConfigValue("downGcic-url"));
					result=JsonToMap.getImageText(param);
				}
			}
		}else if(CommonEnum.Text.getName().equals(MsgType)){
			return null;
		}else if(CommonEnum.Image.getName().equals(MsgType)){//图文消息
			return null;
		}else if(CommonEnum.Voice.getName().equals(MsgType)){//声音消息
			return null;
		}else if(CommonEnum.Link.getName().equals(MsgType)){//链接消息
			return null;
		}else if(CommonEnum.Location1.getName().equals(MsgType)){//地理位置消息
			return null;
		}
	return result;
	}
}
